package client;

//~--- non-JDK imports --------------------------------------------------------
import SessionFactory.SessionFactoryUtil;
import dto.*;

//~--- JDK imports ------------------------------------------------------------


import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.hibernate.SessionFactory;

public class TopicsPosts {

    TopicsHome topicHome = new TopicsHome();
    PostsHome postHome = new PostsHome();
    SectionsHome sectionHome = new SectionsHome();
    ReadmarkHome readMarkHome = new ReadmarkHome();
    private Vector<Topics> innerTopics = new Vector<Topics>();    // to store the topics inside a special section
    // ######### Variable  declaration End ################//
    private Vector<Sections> innerSections = new Vector<Sections>();    // to store the sections(subSections) inside a special section
    // for display //
    private Sections mainForum;             // to store the parent node
    // #######  Amir ############//
    // ######### Getter and Setter for the Private Member Data ###################//

    public Sections getMainForum() {
        return mainForum;
    }

    public void setMainForum(Sections mainForum) {
        this.mainForum = mainForum;
    }

    public Vector<Sections> getInnerSections() {
        return innerSections;
    }

    public void setInnerSections(Vector<Sections> innerSections) {
        this.innerSections = innerSections;
    }

    public Vector<Topics> getInnerTopics() {
        return innerTopics;
    }

    public void setInnerTopics(Vector<Topics> innerTopics) {
        this.innerTopics = innerTopics;
    }

    //=====================================================================================
    public Topics getTopic(Topics topic) // changed from void to Topics
    {
        boolean s = SessionFactoryUtil.getInstance().getCurrentSession().getTransaction().isActive();
        System.out.println("**************************************************************Session is "+ s);
        if(!s)
            SessionFactoryUtil.startNew();
        Topics top = new Topics();
        top = topicHome.getTopic(topic);
        if(!s){
            SessionFactoryUtil.finish();
        }

        return top;
    }
    //======================================================================================

    public Vector<Topics> search(String pattern) {
//        System.out.println("I am insde topicsposts");

        Vector<Topics> topics = new Vector<Topics>();

//        System.out.println("I am insde topicsposts2");

        Topics topic = new Topics();

        topic.setTopicname(pattern);
        SessionFactoryUtil.startNew();
        List results = topicHome.searchpattern(pattern);
        Iterator it = results.iterator();

        while (it.hasNext()) {
            Topics us = (Topics) it.next();

            System.out.println(us.getTopicname());
            System.out.print(us.getSections().getSectionname());
            System.out.print(us.getCreationdate());
            topics.add(us);
            }
        SessionFactoryUtil.finish();

        return topics;
    }
    //===========================================================================================

    public Vector<Topics> search(String pattern, String sectionName) 
    {
        return null;
    }
    //===========================================================================================

    public Integer setPost(Posts post) {
         PostsHome postHome = new PostsHome();
        FilteredpostsHome filterHome = new FilteredpostsHome();
        Calendar          cal        = Calendar.getInstance();
        Date              d          = cal.getTime();
        boolean           filtered   = filterPost(post.getContent());
        System.out.println("filterrrred="+filtered);
        SessionFactoryUtil.startNew();
        if (filtered == false)
        {
            Filteredposts badPost     = new Filteredposts();
            badPost.setFilterdate(d);
            badPost.setJfMembers(post.getJfMembers());
            //topic.setTopicid(null);
            badPost.setTopics(null);
            filterHome.persist(badPost);
            SessionFactoryUtil.commitTrans();
            SessionFactoryUtil.finish();
           
            // topicHome.delete(topic);
            System.out.println("post added on filteredposts table");
            return null;
        }
        else
        {
            Posts myPost = postHome.findById(post.getPostid());
            myPost.setPostdate(d);
            System.out.println("post id afteeeeeeer find by id i ntopicsposts="+myPost.getPostid());
             System.out.println("post conttttten afteeeeeeer find by id i ntopicsposts="+post.getContent());
            Topics myTopic = myPost.getTopics();
            myPost.setContent(post.getContent());
            myTopic.setModifydate(d);
            myPost.setTopics(myTopic);

            postHome.merge(myPost);
            SessionFactoryUtil.commitTrans();
            System.out.println("after commit tranns in topics posts setpost");
            SessionFactoryUtil.finish();
            return myTopic.getTopicid();
        }
        
    }
    //===========================================================================================
         public boolean addPost(Posts post, Topics topic) {

        PostsHome postHome = new PostsHome();
        FilteredpostsHome filterHome = new FilteredpostsHome();
        Calendar cal = Calendar.getInstance();
        Date d = cal.getTime();
        boolean filtered = filterPost(post.getContent());
        System.out.println("filterrrred=" + filtered);
        boolean begin = SessionFactoryUtil.getInstance().getCurrentSession().getTransaction().isActive();
        if (!begin) {
            SessionFactoryUtil.startNew();
        }
        if (filtered == false) {
            Filteredposts badPost = new Filteredposts();
            FilteredpostsHome badPostHome = new FilteredpostsHome();
            badPost.setFilterdate(d);
            badPost.setJfMembers(post.getJfMembers());
            //topic.setTopicid(null);
            badPost.setTopics(null);
            badPost.setContent(post.getContent());
            filterHome.persist(badPost);
            boolean b = SessionFactoryUtil.commitTrans();
            SessionFactoryUtil.finish();
            return false;
        } else {
            System.out.println("insideeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");

            post.setPostdate(d);
            System.out.println("before persist possssst");
            System.out.println(post.getJfMembers().getMemberId());
            System.out.println(post.getTopics().getTopicid());
            Integer x = post.getTopics().getTopicid();
            post.getTopics().setTopicid(x+new Integer(1));
            System.out.println(post.getTopics().getTopicid());
            //post.setTopics(topic);
            System.out.println(post.getContent());
            postHome.persist(post);
            System.out.println("insideeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
            System.out.println("post.gettopics:"+post.getTopics().getTopicid());
            System.out.println(" going to update topic and lurk begore after adding new topic");
            updateTopic(post.getTopics());
            updateReadMark(post.getTopics());

             System.out.println("insideeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");

        }
        boolean b;
        if (!begin) {
            System.out.println("inside !begin to commit trans");
            //Integer x = post.getTopics().getTopicid();
            //post.getTopics().setTopicid(x-new Integer(1));
            //updateTopic(post.getTopics());
            //updateReadMark(post.getTopics());
            b = SessionFactoryUtil.commitTrans();
            System.out.println("b =========== "+b);
            SessionFactoryUtil.finish();
        } else {
            b = true;
        }
        return b;
    }
    
    //===========================================================================================

//    public boolean readmark(Topics topic, JfMembers member) {
//        SessionFactoryUtil.startNew();
//         boolean flag =readMarkHome.getReadMarks(topic, member);
//         if(!flag)
//         {
//              readMarkHome.readmark(topic, member);
//         }
//
//        boolean b = SessionFactoryUtil.commitTrans();
//        SessionFactoryUtil.finish();
//        return flag;
//    }


    public boolean getReadMark(Topics topic, JfMembers member){
        SessionFactoryUtil.startNew();
         boolean flag =readMarkHome.getReadMarks(topic, member);
          boolean b = SessionFactoryUtil.commitTrans();
        SessionFactoryUtil.finish();
        return flag;
    }
     public boolean readmark(Topics topic, JfMembers member) {
        SessionFactoryUtil.startNew();
         boolean flag =readMarkHome.getReadMarks(topic, member);
         if(!flag)
         {
              readMarkHome.readmark(topic, member);
         }

        boolean b = SessionFactoryUtil.commitTrans();
        SessionFactoryUtil.finish();
        return flag;
    }
    //===========================================================================================

    public boolean lurk(Topics topic) {
        SessionFactoryUtil.startNew();
        boolean flag = topicHome.lurk(topic);
        boolean b = SessionFactoryUtil.commitTrans();
        SessionFactoryUtil.finish();
        return b;
    }
    //===========================================================================================

    public Sections getSection(Sections section) // changed from void to Sections
    {
        Sections sec = new Sections();
        SessionFactoryUtil.startNew();
        sec = sectionHome.getSection(section);
        boolean b = SessionFactoryUtil.commitTrans();
        SessionFactoryUtil.finish();
        if (!b) {
            return null;
        }
        return sec;
    }
    //===========================================================================================

    public boolean filterPost(Posts post) {
        return false;
    }

    //======================================== filter post =========================================
    public boolean filterPost(String str) {
        Vector<String> bannedWords = new Vector<String>();

        bannedWords.add("zion");
        bannedWords.add("theocresy");
        bannedWords.add("qewish");/// u can add any bad words here
        System.out.println("in filter post");
        String content = str;
        String[] words = content.split("\\s+");


        for (int i = 0; i < words.length; i++) {
            String[] words2 = words[i].split("<");
            for (int k = 0; k < words2.length; k++) {
                String[] words3 = words2[k].split(">");
                for (int m = 0; m < words3.length; m++) {
                    for (int j = 0; j < bannedWords.size(); j++) {
                        System.out.println("inside for:" + words3[m]);

                        if (words3[m].equals(bannedWords.elementAt(j))) {

                            return false;
                        }
                    }
                }
            }

        }

        return true;
    }
//================================================= //filter post ==================================

    public Integer addTopic(Topics topic, Posts post) {
        //        System.out.println(content);

        System.out.println("i'm insideeeee addTopic agter update");
        Calendar cal = Calendar.getInstance();
        Date d = (java.util.Date) cal.getTime();

        topic.setCreationdate(d);
        topic.setIsclosed(new Integer(0));
        topic.setIspopular(new Integer(0));
        topic.setIssticky(new Integer(0));
        topic.setNumlurkers(new Integer(0));
        topic.setNumofposts(new Integer(0));
        topic.setNumofviews(new Integer(0));

        SessionFactoryUtil.startNew();
        System.out.println(topic.getSections().getSectionid());
        System.out.println(topic.getTopicid());

        //System.out.println("topic iddddd in add topic before persist="+post.getTopics().getTopicid());
        topicHome.persist(topic);
        SessionFactoryUtil.commitTrans();
        SessionFactoryUtil.finish();
       //SessionFactoryUtil.startNew();
       System.out.println(topic.getTopicid());
        System.out.println(topic.getJfMembers().getUsername());
        post.setTopics(topic);
       //SessionFactoryUtil.commitTrans();
       //SessionFactoryUtil.finish();
       SessionFactoryUtil.startNew();
        System.out.println("after topic persisted in topics posts");
        System.out.println("topic iddddd in add topic="+post.getTopics().getTopicid());
        //System.out.println("posttttt iddddd in add topic="+post.getPostid());
        boolean postAdded = addPost(post, topic);

        if (postAdded == false) {   //post contain bad words
//            System.out.println("in addTopic postadded == false");
//            topic.setTopicid(id);
//            topicHome.startNew();//// because trans was closed in addPost()
            SessionFactoryUtil.startNew();
            System.out.println("before deleting topic the id = "+post.getTopics().getTopicid());
            Integer x = post.getTopics().getTopicid();
            post.getTopics().setTopicid(x+new Integer(1));
            topicHome.delete(post.getTopics());
            
        }
        boolean b = SessionFactoryUtil.commitTrans();
        SessionFactoryUtil.finish();
        if(postAdded == false)
        {
            return null;
        }
        else
        {
          return topic.getTopicid();
        }
    }

    //============================================= add Topic ======================================
    public boolean addTopic(Topics topic, Posts post, String content) {
      return true;

    }
//================================================// add Topic ======================================
    // #######  Amir ############//
    // #########  New Method to get Parent Section ########//
    // ## Tested##//

    public boolean getParentSection() {
        SessionFactoryUtil.startNew();
        sectionHome.getParentSection();
        mainForum = sectionHome.getMainForum();
        boolean b = SessionFactoryUtil.commitTrans();
        SessionFactoryUtil.finish();
        return b;
    }

    // #######  Amir ############//
    // #########  New Method to get Inside a special Section ########//
    // ## Tested##//
    public boolean getInsideSection(Sections section) {
        SessionFactoryUtil.startNew();

        sectionHome.getInsideSection(section);
        innerSections = sectionHome.getInnerSections();
        innerTopics = sectionHome.getInnerTopics();
        boolean b = SessionFactoryUtil.commitTrans();
        SessionFactoryUtil.finish();
        return b;
    }

    // ############# Method End #################//
    // ######################### End Of Getter and Setter #####################//
    //==================================== add post=================================================
    public boolean addPost(Posts post, Topics topic, String content) {

       return true;
    }
    //==========================================//add post ===================================

    //========================================// update topic after adding new post ===========
    public boolean updateTopic(Topics topic)
    {
        Calendar cal = Calendar.getInstance();
        Date d = cal.getTime();
        System.out.println("in updatetopic method");
        System.out.println("topic id in update="+topic.getTopicid());
        Topics myTopic = topicHome.findById(topic.getTopicid());
        System.out.println(myTopic.getJfMembers().getUsername());
        Integer numPosts = myTopic.getNumofposts();
        System.out.println("the numPosts ====="+numPosts);
        Integer num = new Integer(1);
        num += numPosts;
        myTopic.setNumofposts(num);
        myTopic.setModifydate(d);
        topicHome.merge(myTopic);
        return true;

    }
//================================================================================================

    public boolean updateReadMark(Topics topic) {

        ReadmarkHome markHome = new ReadmarkHome();
        markHome.getMarks(topic);
        return true;
    }
    //----------------------------------------------------------------------------------
    public Topics getTopicContents(Integer id){
        Topics topics;
        SessionFactoryUtil.startNew();
        topics = topicHome.findById(id);
        Set<Posts> postsS = topics.getPostses();
        Iterator<Posts> postsI = postsS.iterator();
        while(postsI.hasNext()){
            System.out.println(""+postsI.next().getContent());
        }
//        sessionFactory.getCurrentSession().close();
        SessionFactoryUtil.finish();
        return topics;
    }


    ///////////////////////////////////////// Amr Ig //////////////////////////////////////////////
     public Sections getSection(int id) {
         SessionFactoryUtil.startNew();
        Sections section = sectionHome.findById(new Integer(id));
        System.out.println("section name :"+section.getSectionname());
       // SessionFactoryUtil.finish();
        return section;
    }
    

     public Vector<Sections> getParentTree(Sections section) {
        
                Vector<Sections> parents=new Vector<Sections>();
                do{
                    System.out.println("testing........................");
                    if(section.getSections()!=null)
                     parents.insertElementAt(section,0);                     
                     section=section.getSections();
                }while(section!=null);
                sectionHome.finish();
                SessionFactoryUtil.finish();
                return parents;
	}
     //=========================================================================
       public List getallsections()
       {
         SessionFactoryUtil.startNew();
        List sections = sectionHome.getSections();
        SessionFactoryUtil.finish();
        return sections;
       }
     //=========================================================================
}


//~ Formatted by Jindent --- http://www.jindent.com

